<?php
namespace Modules\Backend;

use Phalcon\DiInterface;

class Module implements \Phalcon\Mvc\ModuleDefinitionInterface {
  public function registerAutoloaders(DiInterface $di = null) {
    (new \Phalcon\Loader()) -> registerNamespaces([
      'Components' => APPLICATION_SRC_DIR . '/components',

      __NAMESPACE__ . '\\Controllers' => __DIR__ . '/controllers/',
    ]) -> register();
  }

  public function registerServices(DiInterface $di) {
    $di -> setShared('dispatcher', function() {
      $dispatcher = new \Phalcon\Mvc\Dispatcher();
      $dispatcher -> setDefaultNamespace(__NAMESPACE__ . '\\Controllers');
      return $dispatcher;
    });

    $di -> setShared('config', function() {
      return new \Phalcon\Config(require(APPLICATION_SRC_DIR . '/config/' . APPLICATION_ENV . '.php'));
    });

    $di -> setShared('view', function () {
      return (new \Phalcon\Mvc\View()) -> disable();
    });

    $di -> setShared('db', function () {
      $db = $this -> getShared('config') -> get('DATABASE_MASTER') -> get(0);

      $class = 'Phalcon\\Db\\Adapter\\Pdo\\' . $db -> adapter;
      return new $class([
        'host'     => $db -> host,
        'username' => $db -> username,
        'password' => $db -> password,
        'port'     => $db -> port,
        'dbname'   => $db -> dbname,
        'charset'  => $db -> charset
      ]);
    });

    $di -> setShared('user', function() {
      return \Components\User\Adapter::load([
        'adapter' => 'Sha',
        'Sha' => []
      ]);
    });

    $di -> setShared('staff', function() {
      return \Components\Staff\Adapter::load([
        'adapter' => 'Sha',
        'Sha' => []
      ]);
    });
  }
}
